class DWHelper {
    constructor() {
        this.userName = null;
        this.userID = null;
        this.liveStreamID = null;
        this.replyObserver = null;
        this.replyConfig = null;
        this.commentConfig = null;
        this.commentTimer = null;
        this.explainConfig = null;
        this.explainTimer = null;
        this.expresses = ["[捂脸]",
            "[玫瑰]",
            "[爱心]",
            "[赞]",
            "[666]",
            "[火]",
            "[点点关注]",
            "[我爱你]",
            "[比心]",
            "[庆祝]",
            "[亲亲]",
            "[礼花]",
            "[狮子]",
            "[吃瓜]",
            "[愉快]",
            "[发]",
            "[龇牙]",
            "[干杯]"
        ];
        this.commentMaxSize = 40;
    };
    asySleep(timeout) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve();
            }, timeout);
        });
    }
    asyGet(url) {
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.withCredentials = true;
            xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4)
                    resolve({
                        status: xhr.status,
                        data: xhr.responseText
                    });
            }
            xhr.send();
        });
    };
    asyPost(url, data) {
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            xhr.withCredentials = true;
            xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4)
                    resolve({
                        status: xhr.status,
                        data: xhr.responseText
                    });
            }
            if (typeof data != 'string')
                xhr.send(JSON.stringify(data));
            else
                xhr.send(data);
        });
    };
    async initData() {
        let url = location.href;
        if (url.indexOf('https://zs.kwaixiaodian.com/page/helper') != 0) {
            console.log('网址错误');
            return;
        }
        while (true) {
            let btnList = document.querySelectorAll('button.ant-btn');
            if (btnList.length >= 2) {
                if (btnList[1].innerText == '回到旧版') {
                    console.log('回到旧版');
                    btnList[1].click();
                    return;
                }
                else if (btnList[1].innerText == '进入新版') {
                    console.log('进入新版');
                    break;
                }
            }
            await this.asySleep(100);
        }
        //首先查询用户信息
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/sys/info', '');
        if (status != 200) {
            console.log('查询用户信息失败');
            return;
        }
        data = JSON.parse(data);
        this.userID = data.data.userInfo.sellerId;
        this.userName = data.data.userInfo.sellerNick;
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/live/current/info', '');
        if (status != 200) {
            console.log('查询直播间信息失败');
            return;
        }
        data = JSON.parse(data);
        this.liveStreamID = data.data.liveStreamId;
        console.log(this.userID, this.userName, this.liveStreamID);

        while (true) {
            if (document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer'))
                break;
            await this.asySleep(100);
        }
        console.log('初始化完成');
        //去客户端拉配置信息
        setInterval(() => {
            var bubble = document.querySelector('div[class^=bubble-]');
            if (!bubble)
                return;
            bubble.click();
        }, 1000);
        JSCallInitFinish();
    };
    randExpress() {
        return this.expresses[Math.floor(Math.random() * this.expresses.length)];
    };
    async postReply(userID, commentID, replyContent) {
        if (!this.userID || !this.liveStreamID)
            return;
        var data = {
            liveStreamId: this.liveStreamID,
            replyContent: replyContent,
            commentId: commentID,
            fromUserId: userID
        };
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/comment/reply', data);
        console.log(status, data);
    };
    async postComment(commentContent) {
        if (!this.userID || !this.liveStreamID)
            return;

        var data = {
            liveStreamId: this.liveStreamID,
            commentContent: commentContent
        };
        console.log(new Date(), data);
        var { status, data } = await this.asyPost('https://zs.kwaixiaodian.com/rest/pc/live/assistant/comment/publish', data);
        console.log(status, data);
    };
    getReplyContent(content) {
        for (let reply of this.replyConfig.replies) {
            for (let keyWord of reply.keyWords) {
                if (content.includes(keyWord))
                    return reply.replyContent;
            }
        }
        return null;
    };
    checkReply(value) {
        let key = Object.keys(value).find(key => key.indexOf('__reactProps') == 0);
        if (!key)
            return;
        value = value[key].children.props.data;
        //首先查看是不是自己发出的，如果是自己发出的，就不管了
        let userName = value.fromUserName;
        let userID = value.fromUserId;
        console.log(userID, this.userID, userName);
        if (!userID || this.userID == userID)
            return;
        let commentID = value.commentId;
        if (Math.floor(commentID) <= Math.floor(localStorage.getItem('commentID'))) {
            console.log(commentID, Math.floor(localStorage.getItem('commentID')));
            return;
        }

        localStorage.setItem('commentID', commentID);
        //如果不相同的话，则需要匹配回复
        let commentContent = value.commentContent;
        //开始计算回复内容
        console.log("提问", userName, commentContent);
        let replyContent = this.getReplyContent(commentContent);
        console.log("回复", replyContent);
        //查询是否有对应的内容
        //查询是否有对应的内容
        if (!replyContent) {
            if (this.replyConfig.isWriteFailLog) {
                JSCallReplyWriteFailLog(commentContent);
            }
            return;
        }
        else {
            if (this.replyConfig.isWriteSuccessLog) {
                JSCallReplyWriteSuccessLog(commentContent, replyContent);
            }
        }
        let preReplyContent = "@";
        //是否加密名称
        if (this.replyConfig.isCodeNickName) {
            for (let i = 0; i < userName.length; i++)
                preReplyContent += '*';
        }
        else
            preReplyContent += userName;
        //是否需要切断
        if (this.replyConfig.isCutNickName) {
            let overReplyLength = preReplyContent.length + 1 + replyContent.length - this.commentMaxSize;
            if (overReplyLength > 0) {
                if (overReplyLength < preReplyContent.length - 2) {
                    preReplyContent = preReplyContent.substr(0, preReplyContent.length - overReplyLength);
                    replyContent = preReplyContent + " " + replyContent;
                }
            }
            else
                replyContent = preReplyContent + " " + replyContent;
        }
        else {
            replyContent = preReplyContent + " " + replyContent;
            if (replyContent.length > this.commentMaxSize)
                replyContent = replyContent.substr(0, this.commentMaxSize);
        }
        this.postReply(userID, commentID, replyContent);
    };
    async startReply(config) {
        if (this.replyObserver)
            return;
        if (!document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer'))
            return;
        console.log('开启客服');
        console.log(config);
        this.replyConfig = config;
        document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer').children.forEach((value) => {
            this.checkReply(value);
        });
        //开启监听
        this.replyObserver = new MutationObserver((mutationsList, observer) => {
            // 对变动进行处理
            for (let mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    console.log(mutation.addedNodes.length);
                    mutation.addedNodes.forEach((value) => {
                        this.checkReply(value);
                    });
                }
            }
        });
        this.replyObserver.observe(document.querySelector('div.ReactVirtualized__Grid__innerScrollContainer'), { childList: true });
    };
    stopReply() {
        if (!this.replyObserver)
            return;
        console.log('关闭客服');
        this.replyObserver.disconnect();
        this.replyObserver = null;
    };
    startComment(config) {
        if (this.commentTimer)
            return;
        console.log('开启场控');
        console.log(config);
        this.commentConfig = config;
        if (this.commentConfig.isRandSort)
            this.commentConfig.comments.sort(() => Math.random() - 0.5);
        this.commentConfig.nowIndex = 0;
        if (this.commentConfig.comments.length == 0)
            return;
        this.startCommentTimer();
    };
    startCommentTimer() {
        this.commentTimer = setInterval(async () => {
            var commentContent = this.commentConfig.comments[this.commentConfig.nowIndex++];

            //1到2个表情包
            if (this.commentConfig.isRandPlace) {
                var randExpressNum = Math.floor(Math.random() * 2) + 1;
                for (var i = 0; i < randExpressNum; i++) {
                    var express = this.randExpress();
                    if (commentContent.length + express.length > this.commentMaxSize)
                        break;
                    commentContent += express;
                }
            }
            this.postComment(commentContent);

            if (this.commentConfig.nowIndex >= this.commentConfig.comments.length) {
                clearInterval(this.commentTimer);
                this.commentTimer = null;
                console.log(new Date(), '一轮结束，等待', this.commentConfig.turnWaitTime, '秒');
                this.startCommentTurnTimer();
            }
        }, this.commentConfig.waitTime * 1000);
    };
    startCommentTurnTimer() {
        this.commentTimer = setInterval(async () => {
            clearInterval(this.commentTimer);
            this.commentConfig.nowIndex = 0;
            console.log(new Date(), '一轮开始，等待', this.commentConfig.waitTime, '秒');
            this.startCommentTimer();
        }, this.commentConfig.turnWaitTime * 1000);
    };
    stopComment() {
        if (!this.commentTimer)
            return;
        console.log('关闭场控');
        clearInterval(this.commentTimer);
        this.commentTimer = null;
    };
    startExplain(config) {
        if (this.explainTimer)
            return;
        console.log('开启讲解');
        console.log(config);
        this.explainConfig = config;
        this.explainConfig.nowIndex = 0;
        if (this.explainConfig.indexs.length == 0)
            return;
        this.startExplainTimer();
    };
    startExplainTimer() {
        this.explainTimer = setInterval(async () => {
            var explainIndex = this.explainConfig.indexs[this.explainConfig.nowIndex++];
            this.postExplain(explainIndex);

            if (this.explainConfig.nowIndex >= this.explainConfig.indexs.length)
                this.explainConfig.nowIndex = 0;
        }, this.explainConfig.time * 1000);
    };
    postExplain(index) {
        var explainList = document.querySelectorAll('div[id^=c1goods]');
        for (let explain of explainList) {
            var input = explain.querySelector('input');
            if (!input)
                continue;
            if (input.value == index) {
                var button = explain.querySelector('button');
                console.log(index, button.innerText);
                button.click();
                return;
            }
        }
    };
    stopExplain() {
        if (!this.explainTimer)
            return;
        console.log('关闭讲解');
        clearInterval(this.explainTimer);
        this.explainTimer = null;
    };
};

var dwHelper = new DWHelper();
dwHelper.initData();

